
#include <iostream>
#include <pthread.h>
#include <string>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int tickets = 1000;
struct ThreadData
{
    std::string thread_name_;
    pthread_t thread_id_;
};


pthread_mutex_t lock;

void *Get_Ticket(void *args)
{
    ThreadData *pdata = static_cast<ThreadData *>(args);
    // 进行抢票

    while (1) 
    {         // 先上锁
        pthread_mutex_lock(&lock);
        if (tickets > 0)               // 还有票,可以抢
        {
            // 打印出线程名以及抢到的票编号
            std::cout << pdata->thread_name_ << " is getting  a ticket , the numberr of tickets is " << tickets << std::endl;
            --tickets;
            pthread_mutex_unlock(&lock);    // 解锁
        }
        else
        {
            pthread_mutex_unlock(&lock);    // 解锁
            break;
        }
        usleep(getpid() % 100);
        // 解锁
    }
    return nullptr;
}

int main()
{
    // 初始化互斥锁
    pthread_mutex_init(&lock, nullptr);

    // 模拟10个人抢票的逻辑
    // 即10个线程一起抢票, --tickets表示抢票
    std::vector<ThreadData *> threads;
    for (int i = 0; i < 5; i++)
    {
        ThreadData *pdata = new ThreadData();
        pdata->thread_name_ = "Thread-" + std::to_string(i + 1);
        pthread_create(&pdata->thread_id_, NULL, Get_Ticket, pdata);
        threads.push_back(pdata);
    }

    // 等待所有线程结束
    for (int i = 0; i < threads.size(); i++)
    {
        pthread_join(threads[i]->thread_id_, NULL);
        delete threads[i];
    }

    // 销毁互斥锁
    pthread_mutex_destroy(&lock);

    return 0;
}
